package it.enea.xlab.validation;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * @author fulvio di marco, chiara pezzi, stefano monti
 * @author cristiano novelli
 *
 */
public class JNDIServices {
	
	
	private static ValidationManagerRemote validationManager = null;
	
	private static String ValidationManagerServiceName = "Validation-ear/ValidationManagerImpl/remote";

	
	private static final Map<String, Object> EJB_CACHE = new HashMap<String, Object>();

	
	
	@SuppressWarnings("unchecked")
	public static <T> T retrieveEJB(String key, String name) {
		T ejbBean = null;

		if (EJB_CACHE.containsKey(key)) {
			ejbBean = (T) EJB_CACHE.get(key);
		} else {
			try {
				InitialContext context = new InitialContext();
				ejbBean = (T) context.lookup(name);
				EJB_CACHE.put(key, ejbBean);
			} catch (NamingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return ejbBean;
	}
	

	public static ValidationManagerRemote getValidationManagerService() throws NamingException {
		
		System.out.println("ctx get1");
		
		if (validationManager == null) {
			System.out.println("ctx get2");
			try {
				
				Properties p = new Properties();
				p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
				p.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
				p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
				
				InitialContext ctx = new InitialContext(p);	
				System.out.println("ctx get3");
				
				validationManager = (ValidationManagerRemote) ctx.lookup(ValidationManagerServiceName);
				System.out.println("ctx get4");
			
			} catch (Exception e) {

					e.printStackTrace();
			}
		}		
		
		return validationManager;
	}
	
	
	
}
